<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8" />
    <title></title>
    <style>
      * {
        margin: 0;
        padding: 0;
      }

      .car {
        width: 100px;
        height: 100px;
        background-color: red;
        position: absolute;
        top: 20px;
        left: 30px;
      }

      .box {
        width: 100px;
        height: 100px;
        background-color: green;
        position: absolute;
        right: 120px;
        top: 240px;
      }
    </style>
  </head>
  <body bgcolor="black">
    <div class="car">车</div>
    <div class="box">行人</div>
    <div class="box" style="left: 440px; top: 340px">行人</div>
    <script>
      var car = document.getElementsByClassName("car")[0];
      var box = document.getElementsByClassName("box");
      //移动车
      car.onmousedown = function (ev) {
        var ev = ev || window.event;
        ev.preventDefault();
        //设置鼠标在元素中(car)的中心位置
        var x = ev.pageX - car.offsetLeft;
        var y = ev.pageY - car.offsetTop;
        //移动车  鼠标移动
        document.onmousemove = function (ev) {
          //计算实际移动位置 = 鼠标在可视区域得坐标 - 鼠标在元素中得位置
          var _x = ev.pageX - x;
          var _y = ev.pageY - y;
          //做车的赋值操作
          car.style.left = _x + "px";
          car.style.top = _y + "px";
          //判断是否碰到
          for (var i = 0; i < box.length; i++) {
            var bool = boom(car, box[i]);
            if (bool) {
              box[i].style.backgroundColor = "red";
              box[i].innerHTML = "你撞到我，赔钱";
            } else {
              box[i].style.backgroundColor = "green";
              box[i].innerHTML = "行人";
            }
          }
        };
        //鼠标松开事件
        document.onmouseup = function () {
          document.onmousemove = null;
        };
      };
      //封装碰撞函数
      function boom(obj1, obj2) {
        //obj1车 obj2代表人
        //obj1的四个偏移量
        var l1 = obj1.offsetLeft;
        var t1 = obj1.offsetTop;
        var r1 = obj1.offsetLeft + obj1.offsetWidth;
        var b1 = obj1.offsetTop + obj1.offsetHeight;
        //obj2的四个偏移量
        var l2 = obj2.offsetLeft;
        var t2 = obj2.offsetTop;
        var r2 = obj2.offsetLeft + obj2.offsetWidth;
        var b2 = obj2.offsetTop + obj2.offsetHeight;
        //碰撞条件的达成
        if (r1 >= l2 && l1 <= r2 && b1 >= t2 && t1 <= b2) {
          return true;
        } else {
          return false;
        }
      }
    </script>
  </body>
</html>
